package com.basker.pisces.domain.property;

import org.springframework.util.StringUtils;

import com.basker.pisces.domain.entity.meta.AbstractEntity;
import com.basker.pisces.domain.entity.meta.Entity;
import com.basker.pisces.domain.property.meta.Property;
import com.basker.pisces.utils.ReflectionUtils;

public class PropertyFactory {
    public static <TProperty extends Property<?>> TProperty create(AbstractEntity hostEntity,
                                                                   Class<TProperty> propertyType, String propertyName) {
        return create(hostEntity, propertyType, propertyName, null);
    }

    public static <TProperty extends Property<?>> TProperty create(AbstractEntity hostEntity,
                                                                   Class<TProperty> propertyType, String propertyName,
                                                                   String alias) {
        TProperty property = ReflectionUtils.createNewInstance(propertyType);

        property.setName(propertyName);
        property.setAlias(getAlias(hostEntity, propertyName, alias));

        property.setHostEntity(hostEntity);
        property.initial();

        return property;
    }

    private static String getAlias(AbstractEntity hostEntity, String propertyName, String alias) {
        if (StringUtils.isEmpty(alias)) {
            if (hostEntity instanceof Entity) {
                alias = propertyName;
            } else {
                alias = hostEntity.getName() + "." + propertyName;
            }
        }

        return alias;
    }

}
